package com.example.security.funtion;

import com.example.core.constant.Constant;
import com.example.core.po.BasePo;
import com.example.core.utils.StringUtils;
import com.googlecode.aviator.runtime.type.AviatorBoolean;
import com.googlecode.aviator.runtime.type.AviatorObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Field;
import java.util.Map;


/****
 * @AuthMethod(expression = "FieldPropertyFunction('jobClass','com.example.sys.job.quartz.TestJob')")
 * 校验属性的校验器
 */
@Service
public class FieldPropertyFunction extends SysAbstractFunction {

    Logger logger = LoggerFactory.getLogger(getClass());

    @Override
    public AviatorObject call(Map<String, Object> env, AviatorObject propertys, AviatorObject values) {
        String property = propertys.stringValue(env);
        String value = values.stringValue(env);
        if (env instanceof FunctionContext) {
            FunctionContext functionContext = (FunctionContext) env;
            HttpServletRequest httpServletRequest = functionContext.getHttpServletRequest();
            if (httpServletRequest != null && StringUtils.isNotEmpty(httpServletRequest.getParameter(Constant.ID))) {
                String id = httpServletRequest.getParameter(Constant.ID);
                BasePo po = (BasePo) functionContext.getBaseService().getById(id);
                if (po != null) {
                    try {
                        Field field = po.getClass().getDeclaredField(property);
                        field.setAccessible(true);
                        if (field.get(po).toString().equalsIgnoreCase(value)) {
                            return AviatorBoolean.TRUE;
                        }
                    } catch (Exception e) {
                        logger.warn("FieldPropertyFunction 获取 Po:" + po.getClass().getName() + "对应的: " + property + "的属性失败，抛出异常，请检查配置信息." + e.getMessage());
                    }
                }
            }
        }
        return AviatorBoolean.FALSE;
    }
}
